<?php

require '../data/data.php';

//只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	header('HTTP/1.1 405 Method Not Allowed');
	return;
}

//开启session
session_start();

//接收登录信息
$username = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password']) : '';

//初始化错误包
$isError = false;
$errorBag = [
	'username' => '',
	'password' => ''
];

//判断填写的注册信息是否符合规范
if (trim($username) === '') {
	$isError = true;
	$errorBag['username'] = '用户名不能为空';
}elseif (trim($password) === '') {
	$isError = true;
	$errorBag['password'] = '密码不能为空';
}

//判断用户和密码是否匹配
if ($isError === false) {
	//判断数据库是否存在该用户
	$sql = 'select id, user_name, password from `users` where user_name = ?';
	$data = query($sql, [$username]);
	if (count($data) > 0) {
		//判断用户密码与输入密码是相同
		$user = $data[0];
	    if (password_verify($password, $user['password'])) {
	      	// 密码正确, 做登录正确的处理
	      	$hasError = false;
	      	// 修改登录时间和ip
	      	$ip = $_SERVER['REMOTE_ADDR'];
	      	//将登录信息写进数据库
	      	$sql = 'update users set last_login=now(),last_login_ip=? where id=?';
        	$args = [$ip, $user['id']];
        	 execute($sql, $args);
      		//用户密码验证通过，把用户信息存入session，意味已登录
		     $_SESSION['user'] = $user;
		     header('Location:../index.php');
		     return;
        }else {
        	$isError = true;
			$errorBag['password'] = '密码错误';
        }
	}else {
		$isError = true;
		$errorBag['username'] = '该用户名不存在';
	}
}

//将错误包返回到登录页面
if ($isError) {
	$_SESSION['is_error'] = $isError;
	$_SESSION['error_bag'] = $errorBag;
	header('Location:../login.php');
	return;
}